package com.zcy.nidavellir.multilogin.login

import android.app.Activity
import android.content.Intent
import com.facebook.internal.Utility.logd
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.zcy.nidavellir.multilogin.R
import com.zcy.nidavellir.multilogin.Utils.log
import com.zcy.nidavellir.multilogin.Utils.toast
import com.zcy.nidavellir.multilogin.proxy.ILogin
import java.lang.ref.WeakReference

/**
 * @author:       zhaocy
 * @description:  ${DESP}
 * @date:         2018/9/29
 */
class GoogleLoginImpl(private val weakReference: WeakReference<Activity>) :ILogin {
    private var mGoogleSignInClient: GoogleSignInClient? = null
    private val RC_SIGN_IN = 9001

    override fun loginRequest(context: Activity, authToken: String) {
        super.loginRequest(context, authToken)
        weakReference?.get()?.toast("Google log in success authToken = $authToken")
        log("Google log in success authToken = $authToken")
    }
    override fun action() {
        weakReference.get()?.let {
            val client_id = it.getString(R.string.google_login_server_client_id)
            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestIdToken(it.getString(R.string.google_login_server_client_id))
                .build()
            mGoogleSignInClient = GoogleSignIn.getClient(it, gso)

            val signInIntent = mGoogleSignInClient?.signInIntent
            it.startActivityForResult(signInIntent, RC_SIGN_IN)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            handleSignInResult(task)
        }

    }
    private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
        try {
            val account = completedTask.getResult(ApiException::class.java!!)
            account?.let {
                loginRequest(weakReference?.get() ?: return@let, it.idToken!!)
            }

        } catch (e: ApiException) {
        }

    }

}